<template>
  <div class="app-container">
    <div class="search-bar">
      <!-- 拆线呢字段项 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="字典项名称" prop="label">
          <el-input
            v-model="queryParams.label"
            placeholder="字典项名称"
            clearable
            style="width: 190px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="字典项值" prop="value">
          <el-input
            v-model="queryParams.value"
            placeholder="字典项值"
            clearable
            style="width: 190px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input
            v-model="queryParams.dictType"
            placeholder="字典类型"
            clearable
            style="width: 190px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="字典描述" prop="description">
          <el-input
            v-model="queryParams.description"
            placeholder="字典描述"
            clearable
            style="width: 190px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属字典" prop="dictId">
          <el-select
            v-model="queryParams.dictId"
            placeholder="请选择"
            clearable
            style="width: 190px"
          >
            <el-option
              v-for="item in dictList"
              :key="item.id"
              :label="item.dictType"
              :value="<any>item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="search" @click="handleQuery()">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <!-- 操作字段项 -->
      <div class="mb-10px">
        <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
        <el-button type="primary" icon="delete" @click="exportExcel()">导出</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="DictItemList"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column prop="label" label="字典项名称" min-width="200" />
        <el-table-column prop="value" label="字典项值" width="200" />
        <el-table-column prop="dictId" label="所属字典" width="200">
          <template #default="scope">{{ getDictName(scope.row.dictId) }}</template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="200">
          <template #default="scope">{{ scope.row.sortOrder == 0 ? '升序' : '降序' }}</template>
        </el-table-column>
        <el-table-column prop="dictType" label="字典类型" min-width="200" />
        <el-table-column prop="description" label="字典描述" width="200" />
        <el-table-column prop="remarks" label="备注" width="200" />
        <el-table-column prop="createBy" label="创建人" width="200" />
        <el-table-column prop="createTime" label="创建时间" width="200" />
        <el-table-column prop="updateBy" label="修改人" width="200" />
        <el-table-column prop="updateTime" label="更新时间" width="200" />
        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-if="pageInfo.total > 0"
        v-model:total="pageInfo.total"
        v-model:page="pageInfo.current"
        v-model:limit="pageInfo.size"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="400px"
      @closed="handleCloseDialog"
    >
      <el-form ref="DictItemFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="字典项名称" prop="label" label-width="100px">
          <el-input v-model="formData.label" placeholder="请输入字典项名称" />
        </el-form-item>
        <el-form-item label="字典项值" prop="value" label-width="100px">
          <el-input v-model="formData.value" placeholder="请输入字典项值" />
        </el-form-item>
        <el-form-item label="所属字典" prop="dictId" label-width="100px">
          <el-select v-model="formData.dictId" placeholder="请选择所属字典">
            <el-option
              v-for="item in dictList"
              :key="item.id"
              :label="item.dictType"
              :value="<any>item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder" label-width="100px">
          <el-select v-model="formData.sortOrder" placeholder="请选择排序">
            <el-option
              v-for="item in sortOrder"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType" label-width="100px">
          <el-input v-model="formData.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="字典描述" prop="description" label-width="100px">
          <el-input v-model="formData.description" placeholder="请输入字典描述" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks" label-width="100px">
          <el-input v-model="formData.remarks" placeholder="请输入备注" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'DictItem',
  inheritAttrs: false,
});

import DictItemAPI, { DictItemVO } from '@/api/system/dictItem.api';
import DictAPI, { DictVO } from '@/api/system/dict.api';
import { toRaw } from 'vue';
// 特殊字段项
const route = useRoute();
const queryFormRef = ref();
const DictItemFormRef = ref();
const sortOrder = reactive([
  { label: '升序', value: 0 },
  { label: '降序', value: 1 },
]);
const loading = ref(false);
const queryParams = reactive<DictItemVO>({});
const pageInfo = reactive({
  current: 1,
  size: 10,
  total: 0,
});
const dialog = reactive({
  title: '新增',
  visible: false,
});
const DictItemList = ref<DictItemVO[]>();
const formData = ref<DictItemVO>({
  dictType: '',
  description: '',
  remarks: '',
});
watch(formData, () => {
  dialog.title = formData.value.id ? '编辑' : '新增';
});
const rules = reactive({
  label: [{ required: true, message: '字典项名称不能为空', trigger: 'blur' }],
  value: [{ required: true, message: '字典项值不能为空', trigger: 'blur' }],
  dictId: [{ required: true, message: '所属字典不能为空', trigger: 'blur' }],
  dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }],
  description: [{ required: true, message: '字典描述不能为空', trigger: 'blur' }],
  remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
});
// 已选择的字典项ID
const selectDictItemIds = ref<number[]>([]);
function handleSelectionChange(selection: any) {
  selectDictItemIds.value = selection.map((item: any) => item.id);
}
// 查询字段项
function handleQuery({ page: current } = { page: 1 }) {
  loading.value = true;
  const param: any = {
    ...toRaw(queryParams),
    ...toRaw(pageInfo),
    current,
  };
  if (current) {
    pageInfo.current = current;
  }
  for (const key in param) {
    if (param[key] === undefined || param[key] === null || param[key] === '') {
      delete param[key];
    }
  }
  DictItemAPI.getList(param).then((data: any) => {
    DictItemList.value = data.records;
    pageInfo.total = data.total;
    loading.value = false;
  });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
// function handleSelectionChange(selection: any) {
//   selectIds.value = selection.map((item: any) => item.id);
// }

/**
 * 打开字段项弹窗
 *
 * @param parentId 父字段项ID
 * @param DictItemId 字段项ID
 */
async function handleOpenDialog(newDictItem?: DictItemVO) {
  if (newDictItem) {
    formData.value = { ...newDictItem };
  }
  dialog.visible = true;
}

// 提交字段项表单
function handleSubmit() {
  DictItemFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const DictItemId = <number>formData.value.id;
      if (DictItemId) {
        DictItemAPI.update(formData.value)
          .then(() => {
            ElMessage.success('修改成功');
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        const param = { ...formData.value };
        param.id = Date.now();
        DictItemAPI.create(param)
          .then(() => {
            ElMessage.success('新增成功');
            handleCloseDialog();
            resetForm();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除字段项
function handleDelete(id: number) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(
    () => {
      loading.value = true;
      DictItemAPI.deleteById(id)
        .then(() => {
          ElMessage.success('删除成功');
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info('已取消删除');
    }
  );
}

// 重置表单
function resetForm() {
  DictItemFormRef.value.resetFields();
  DictItemFormRef.value.clearValidate();

  formData.value.id = undefined;
  formData.value.dictType = undefined;
  formData.value.description = undefined;
  formData.value.remarks = undefined;
  formData.value.dictId = dictList.value?.[0]?.id;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  if (dialog.title === '编辑') {
    resetForm();
  }
}
// 获取字典列表
const dictList = ref<DictVO[]>();
async function getDictList() {
  const data = await DictAPI.getListAll();
  dictList.value = data;
}
function getDictName(dictId: string) {
  if (!dictId) {
    return '-';
  }
  const dict = dictList.value?.find((item) => item.id === dictId);
  return dict?.dictType || '-';
}
// 导出字典项
function exportExcel() {
  const param: any = { ...toRaw(queryParams) };
  for (const key in param) {
    if (param[key] === undefined || param[key] === null || param[key] === '') {
      delete param[key];
    }
  }
  DictItemAPI.epoxrtExcel(param).then((res: any) => {
    const url = window.URL.createObjectURL(res.data);
    window.open(url, '_blank');
  });
}
onMounted(async () => {
  await getDictList();
  if (route.query.id) {
    queryParams.dictId = <string>route.query.id;
  }
  handleQuery();
});
</script>
